<template>
    <view class="charge-payment pd-v-24 pd-h-20">
        
        <view class="charge-payment__header pd-v-24 pd-t-32 pd-b-24 bg-white border8">
            <view class="flex flex-end">
                <view class="price font52 lh-52 color-default flex flex-end">
                    <view class="font32 lh-32">
                        ￥
                    </view>
                        {{storeDetail.chargeFee}}
                </view>
                <view class="flex-1 unit font28 lh-28 color-default">
                    /度+服务费
                </view>
            </view>

            <view class="font32 lh-44 color-default bold mr-t-32 " @click="callPhone(storeDetail.repairPhone)">
                {{deviceInfo.deviceName}}{{ storeDetail.repairPhone ? `（${storeDetail.repairPhone}）` : ''}}
            </view>

            <view class="mr-t-16 font26 lh-36 color-info">
                {{storeDetail.spliceAddress}}
            </view>
              
              
        </view>

        <view class="charge-payment__body">
            <view class="pd-v-24 pd-b-24 pd-t-36 bg-white border8 mr-t-20">
                <view class="font28 lh-40 bold color-default">
                    充电模式
                </view>
                <view class="flex mr-t-24 flex-j-center">
                    <view class="button-class">
                        <u-button plain :color="activeMode == 1 ? '#35BE65' : '#A4A6A5'" text="充满自停" @click="chargeMode(1)"></u-button>
                    </view>
                    
                    <view class="button-class">
                        <u-button plain :color="activeMode == 2 ? '#35BE65' : '#A4A6A5'" text="定额充电" @click="chargeMode(2)"></u-button>
                    </view>

                </view>
                  

                

                <u--form
                    v-if="activeMode == 2"
                    labelPosition="left"
                    labelWidth="80"
                    ref="uForm"
                >
                    <u-form-item
                        label="充电费用"
                        borderBottom
                    >
                        <u--input
                            v-model="chargeCost"
                            type="digit"
                            placeholder="请输入充电费用"
                            border="none"
                             :customStyle="{backgroundColor:'#F5F5F5',height:'84rpx',padding:'0 24rpx'}"
                             inputAlign="right"
                            suffixIcon="rmb"
                        ></u--input>
                    </u-form-item>
                </u--form>
                  
            </view>

            
            <view class="pd-v-24 pd-b-24 pd-t-36 bg-white border8 mr-t-20">
                <view class="font28 lh-40 bold color-default">
                    支付方式
                </view>
                <view class="flex mr-t-24  flex-j-center">
                    <view class="button-class">
                        <u-button disabled plain :color="activePaymentMethod == 1 ? '#35BE65' : '#A4A6A5'" text="微信信用支付" @click="chargePaymentMethod(1)"></u-button>
                        <view class="flex flex-center mr-t-12">
                          <image src="../../static/logo.png" style="width:32rpx;" mode="widthFix"></image>
                          <view class="flex-1 mr-l-11 wechat-pay-text font24 lh-24 flex flex-center">
                            微信支付分
                            <view class="wechat-pay-line mr-v-11"></view>
                            先充后付
                          </view>
                        </view>
                        <view class="wechat-pay-desc font22 lh-22 mr-t-8">550分及以上优享</view>
                    </view>
                    
                    <view class="button-class">
                        <u-button plain :color="activePaymentMethod == 2 ? '#35BE65' : '#A4A6A5'" :text="`钱包支付(¥${balance})`" @click="chargePaymentMethod(2)"></u-button>
                    </view>
                </view>
                  
                  
            </view>
              
        </view>


        <view class="charge-payment__footer mr-t-40 pd-v-52">
            
            <u-button type="primary" shape="circle" color="#35BE65" text="充电" @click="goCharge"></u-button>
        </view>
          
        
        <reChargeComponent ref="reChargeComponentRef" @confirm="confirm"></reChargeComponent>
          
  </view>
</template>

<script setup>

import { useStore } from '@/store/index.js';
import { getEquipmentsByCodeAndPort,getDeviceInfoById,getStoreInfoByDeviceCode } from "@/api/index/index.js";

import { computed, ref, onMounted, reactive,defineProps } from "vue";
import reChargeComponent from '@/components/reCharge.vue'
import { onLoad,onShow } from '@dcloudio/uni-app';
import { walletBalance,recharge,startCharging } from '@/api/user.js'

const store = useStore();
const props = defineProps({
    deviceNumber: {
        type: String,
        default: ''
    },
    port: {
        type: String,
        default: ''
    },
    storeId: {
        type: String,
        default: ''
    }
})
const balance = ref(0)
const deviceInfo = ref({})
const storeDetail = ref({})

const isWx = ref(false)
const redirectURL = ref('/pages/index/index')
const list = ref([{isUsed:false},{isUsed:true},{isUsed:true},{isUsed:true},{isUsed:false},{isUsed:false},{isUsed:false},{isUsed:false},])
const activeMode = ref(1)
const activePaymentMethod = ref(2)
const reChargeComponentRef = ref(null)
const deviceId = ref('')
const chargeCost = ref(0)


onLoad(() => {
    equipmentsByCodeAndPort()
    getStoreInfoByDeviceCodeFn()
    
});

onShow(() => {
  if(store?.user?.token) {
        getWalletBalance()
    }
})


const getStoreInfoByDeviceCodeFn = () => {
    getStoreInfoByDeviceCode({code:props.deviceNumber}).then(res => {
        console.log(res,'resssssss')
        if(res.code == 200) {
            storeDetail.value = res.data
            deviceId.value = res.data.deviceId

            getDeviceById()
        }
    })
}

const getDeviceById = () => {
    getDeviceInfoById({id:props.deviceId || deviceId.value}).then(res => {
        console.log(res,'res')
        if(res.code == 200) {
            deviceInfo.value = res.data
        }
    })
}

const getWalletBalance = () => {
    walletBalance().then(res => {
        
        if(res.code == 200) {
            balance.value = res.data
        }
    })
}


const equipmentsByCodeAndPort = () => {
    getEquipmentsByCodeAndPort({
        code: props.deviceNumber,
        port: props.port
    }).then(res => {
        console.log(res,'res')
    })
}

const chargeMode = (mode) => {
    activeMode.value = mode
}

const chargePaymentMethod = (method) => {
    activePaymentMethod.value = method
}


const goCharge = () => {
    console.log(activeMode.value,'activeMode.value')
    console.log(activePaymentMethod.value,'activePaymentMethod.value')
    
      if(activeMode.value == 2) {
          if(chargeCost.value <= 0) {
              uni.showToast({
                  title: '请输入充电费用',
                  icon: 'none'
              })

              return;
          } 


          let isNumberReg = /^\d+(\.\d{1,2})?$/

          if(!isNumberReg.test(chargeCost.value)) {
            uni.showToast({
                title: '请输入正确的金额',
                icon: 'none'
            })
            return
          }

          if(balance.value == 0) {
            uni.showModal({
                  title: '提示',
                  content: '余额不足,请进行充值',
                  success: function (res) {
                      if (res.confirm) {
                          reChargeComponentRef.value.show()
                      }
                  }
              })
            return;
          }

          if(activePaymentMethod.value == 2 && chargeCost.value > balance.value) {
              uni.showModal({
                  title: '提示',
                  content: '钱包余额不足,请进行充值',
                  success: function (res) {
                      if (res.confirm) {
                          reChargeComponentRef.value.show()
                      }
                  }
              })
              return;
          }
      } else if(activeMode.value == 1) {
        if(balance.value < 2) {
              uni.showModal({
                  title: '提示',
                  content: '余额不足,至少2元才可以进行充电',
                  success: function (res) {
                      if (res.confirm) {
                          reChargeComponentRef.value.show()
                      }
                  }
              })

              return;
        }
      }
      if(activePaymentMethod.value == 2) { //钱包支付
          if(balance.value <= 0) {

              // uni.showModal({
              //     title: '提示',
              //     content: '余额不足,至少2元才可已进行充电',
              //     success: function (res) {
              //         if (res.confirm) {
              //             reChargeComponentRef.value.show()
              //         }
              //     }
              // })
              reChargeComponentRef.value.show()
              return
          } else {
            uni.requestSubscribeMessage({
              tmplIds: ['dlq83L949BoXVEreLBbOi2m02eRA5PTTbhNGIcAbxyo'],
              success: function (res) { 
                console.log(res,'resssssssss')
              },
              fail: function (err) { 
                console.log(err,'errrrrrrrrr')
              },

              complete: function (res) { 
                uni.showLoading({
                    title: '正在支付'
                })
                startCharging({
                    "deviceId": props.deviceId || deviceId.value,
                    "port": props.port,
                    "payType": activePaymentMethod.value,
                    "chargeMode": activeMode.value,
                    "quota": activePaymentMethod.value == 2 ? chargeCost.value : undefined
                }).then(res => {
                    uni.hideLoading()
                    console.log(res,'res')
                    if(res.code == 200) {
                        uni.showToast({
                            title: '支付成功，开始充电',
                            icon: 'none',
                            success: function () {
                                uni.redirectTo({
                                    url: '/sub_user/pages/chargeDetail/chargeDetail?orderId='+res.data
                                })
                            }
                        })
                    } else {
                        // uni.showToast({
                        //     title: res.msg,
                        //     icon: 'none'
                        // })

                        uni.showModal({
                            title: '提示',
                            content: res.msg,
                            showCancel: false
                        })

                    }
                }).catch(err => {
                    uni.hideLoading()
                    console.log(err,'err')
                })
              }
          })
        }
      } else if(activePaymentMethod.value == 1){ //信用分支付
        uni.requestSubscribeMessage({
          tmplIds: ['dlq83L949BoXVEreLBbOi2m02eRA5PTTbhNGIcAbxyo'],
          success: function (res) { 
            console.log(res,'resssssssss')
          },
          fail: function (err) { 
            console.log(err,'errrrrrrrrr')
          },

          complete: function (res) { 
              uni.showLoading({
                  title: '正在支付'
              })
              startCharging({
                  "deviceId": props.deviceId || deviceId.value,
                  "port": props.port,
                  "payType": activePaymentMethod.value,
                  "chargeMode": activeMode.value,
                  "quota": activePaymentMethod.value == 2 ? chargeCost.value : undefined
              }).then(res => {
                  uni.hideLoading()
                  
                  uni.showToast({
                      title: '支付成功，开始充电',
                      icon: 'none',
                      success: function () {
                          uni.redirectTo({
                              url: '/sub_user/pages/chargeDetail/chargeDetail?orderId='+res.data
                          })
                      }
                  })
                  console.log(res,'eeee')
              }).catch(err => {
                  uni.hideLoading()
                  console.log(err,'err')
              })
          }
        })
      }
    
}



const confirm = (e) => {
    console.log(e,'eeeeee')
    uni.showLoading({
        title: '正在支付'
    })
    recharge(e).then(res => {
        console.log(res,'ssssssssssss')
        uni.hideLoading()
        if(res.code == 200) {
            uni.requestPayment({
                provider: 'wxpay',
                timeStamp: res.data.timeStamp+'',
                nonceStr: res.data.nonceStr,
                package: res.data.prepayId,
                signType: 'RSA',
                paySign: res.data.paySign,
                success: function (res) {
                    uni.showToast({
                        title: '支付成功',
                        icon: 'success',
                        duration: 2000
                    })
                    getWalletBalance()
                },
                fail: function (res) {
                    uni.showToast({
                        title: '取消支付',
                        icon: 'none',
                        duration: 2000
                    })
                }
            })
        }else {
                              uni.showToast({
                                  title: res.msg,
                                  icon: 'none'
                              })
                          }
    }).catch(err => {
        console.log(err,'err')  
        uni.hideLoading()
        uni.showToast({
            title: '支付失败',
            icon: 'none',
            duration: 2000
        })
    })
    
    // setTimeout(() => {
    //     uni.hideLoading()
    //     uni.showToast({
    //         title: '支付成功',
    //         icon: 'success',
    //         duration: 2000
    //     })
    // }, 2000)
}



const callPhone = (num) => {
    uni.makePhoneCall({
        phoneNumber: num,
        success: function () {
            console.log('success');
        },
        fail: function () {
            console.log('fail');
        }
    });
}

</script>

<style lang="scss" scoped>
.charge-payment {
    background: #F5F5F5;
    min-height:100vh;

    

    .charge-payment__header {
        .price {
            color:rgba(43, 153, 81, 1);
        }
    }

    .charge-payment__body {
        .button-class {
            margin:0 8rpx;
            flex:1;
        }
    }


    .wechat-pay-text {
      color:rgba(102,102,102,1);
    }

    .wechat-pay-line {
      width:1px;
      height:24rpx;
      background:rgba(102,102,102,0.6);
    }

    .wechat-pay-desc {
      color:rgba(102,102,102,0.6);
    }
} 
</style>
